import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/music_source.dart';

class ApiTestHelper {
  static const String baseUrl = 'https://music-api.gdstudio.xyz/api.php';
  
  // 请求超时时间
  static const Duration _timeout = Duration(seconds: 15);
  
  // 通用请求头
  static const Map<String, String> _headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache',
    'Connection': 'keep-alive',
  };

  /// 测试API连接性
  static Future<void> testApiConnection() async {
    print('=== 开始测试API连接性 ===');
    
    try {
      // 测试搜索功能
      await testSearch();
      
      // 测试获取播放链接
      await testGetUrl();
      
    } catch (e) {
      print('API测试失败: $e');
    }
    
    print('=== API测试完成 ===');
  }

  /// 测试搜索功能
  static Future<void> testSearch() async {
    print('\n--- 测试搜索功能 ---');
    
    final uri = Uri.parse(baseUrl).replace(queryParameters: {
      'types': 'search',
      'source': 'netease',
      'name': '周杰伦',
      'count': '5',
      'pages': '1',
    });

    print('请求URL: $uri');
    
    try {
      final response = await http.get(uri, headers: _headers).timeout(_timeout);
      print('响应状态码: ${response.statusCode}');
      print('响应内容: ${response.body}');
      
      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        if (jsonData is List && jsonData.isNotEmpty) {
          print('搜索成功，找到 ${jsonData.length} 首歌曲');
          final firstSong = jsonData[0];
          print('第一首歌曲信息: $firstSong');
        } else {
          print('搜索结果为空或格式异常');
        }
      } else {
        print('搜索请求失败');
      }
    } catch (e) {
      print('搜索测试出错: $e');
    }
  }

  /// 测试获取播放链接
  static Future<void> testGetUrl() async {
    print('\n--- 测试获取播放链接 ---');
    
    // 使用一个已知的歌曲ID进行测试
    final uri = Uri.parse(baseUrl).replace(queryParameters: {
      'types': 'url',
      'source': 'netease',
      'id': '186016',  // 周杰伦 - 稻香
      'br': '320',
    });

    print('请求URL: $uri');
    
    try {
      final response = await http.get(uri, headers: _headers).timeout(_timeout);
      print('响应状态码: ${response.statusCode}');
      print('响应内容: ${response.body}');
      
      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        if (jsonData is Map && jsonData.containsKey('url')) {
          final url = jsonData['url'];
          print('获取播放链接成功: $url');
        } else {
          print('响应中没有url字段，完整响应: $jsonData');
        }
      } else {
        print('获取播放链接请求失败');
      }
    } catch (e) {
      print('获取播放链接测试出错: $e');
    }
  }

  /// 测试不同音乐源
  static Future<void> testDifferentSources() async {
    print('\n--- 测试不同音乐源 ---');
    
    final sources = ['netease', 'tencent', 'kugou', 'kuwo'];
    
    for (final source in sources) {
      print('\n测试音乐源: $source');
      
      final uri = Uri.parse(baseUrl).replace(queryParameters: {
        'types': 'search',
        'source': source,
        'name': '周杰伦',
        'count': '1',
        'pages': '1',
      });

      try {
        final response = await http.get(uri, headers: _headers).timeout(_timeout);
        print('$source - 状态码: ${response.statusCode}');
        
        if (response.statusCode == 200) {
          final jsonData = json.decode(response.body);
          if (jsonData is List && jsonData.isNotEmpty) {
            print('$source - 搜索成功');
          } else {
            print('$source - 搜索结果为空');
          }
        } else {
          print('$source - 请求失败');
        }
      } catch (e) {
        print('$source - 测试出错: $e');
      }
    }
  }
}